package com.csxy.zqm.controller;

import com.csxy.zqm.JwtUtils;
import com.csxy.zqm.R;
import com.csxy.zqm.entity.UcenterMember;
import com.csxy.zqm.entity.vo.LoginVo;
import com.csxy.zqm.entity.vo.RegisterVo;
import com.csxy.zqm.entity.vo.UcenterMemberVo;
import com.csxy.zqm.exception.MyException;
import com.csxy.zqm.service.UcenterService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/serviceUcenter/ucenter")
public class UcenterController {
    @Autowired
    private UcenterService ucenterService;
    //登录
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo){
        //返回token 用jwt生成
        System.out.println(loginVo.getPassword()+loginVo.getPhone());
        String token = ucenterService.login(loginVo);
        return R.ok().data("token",token);
    }

    //注册
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo registerVo){
        ucenterService.register(registerVo);
        return R.ok();
    }
    //根据token获取用户信息
    @GetMapping("/getUserInfoForJwt/")
    public R getUserInfoForJwt(HttpServletRequest request){
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //查询数据库，根据用户id，获取用户信息
        UcenterMember member = ucenterService.getById(memberId);
        return R.ok().data("userInfo",member);
    }
    //根据用户id查询用户信息
    @PostMapping("/getMemberInfoById/{memberId}")
    public UcenterMemberVo getMemberInfoById(@PathVariable String memberId){
        UcenterMember member = ucenterService.getById(memberId);
        if (member == null){
            throw new MyException(20001,"用户不存在"); //明确抛出异常触发Feign错误
        }
        UcenterMemberVo memberVo = new UcenterMemberVo();
        BeanUtils.copyProperties(member,memberVo);
        return memberVo;
    }
    //根据日期，获取当天注册人数
    @GetMapping("/countRegister/{day}")
    public R countRegister(@PathVariable String day){
        Integer count = ucenterService.getCountRegister(day);
        return R.ok().data("countRegister",count);
    }
}
